const { Add, Update, QueryOne, Execsql_Count, Exec, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/feedback');
var { formatDateYear, formatDateTime } = require('../libs/common');
var _ = require('underscore');
const logger = require('../libs/log').logger;

// 反馈
async function feedAdd(doc) {
  try {
    let isdone = await QueryOne('hzz_feedbacks', { pcode: doc.pcode, fcode: doc.fcode });
    if (!!isdone) {
      await Update('hzz_feedbacks', format(_.extend(doc, { id: isdone.id })));
    } else {
      await Add('hzz_feedbacks', init(doc));
    }
    return {
      code: 0,
      msg: '平台已收到您的反馈，谢谢'
    }
  } catch (error) {
    logger.error('-----feedAdd----反馈异常,error', error)
    return {
      code: 1,
      msg: '反馈异常,请联系客服'
    }
  }
}
// 反馈列表
async function feedList(req) {
  try {
    let { userphone, userrole } = req.headers;
    let isenterprise = userrole ? userrole.split(',').includes('enterprise') : false;
    let { pagenum, pagesize } = req.body;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let pcodelists;
    // 如果是外联合作推荐人角色，并且绑定手机号的，只查询自己用户信息
    if(isenterprise && userphone){
      let da1= await ExecGetOne(`select pcode from hzz_inviterhistories where phone ='${userphone}'`);
      if(da1){
        let pps = await Exec(`select code from hzz_peoples where invitcode='${da1.pcode}'`);
        pcodelists = _.pluck(pps,'code');
      }
    }
    let sql = `SELECT * FROM hzz_feedbacks `;
    let sql_filter='';
    if(pcodelists){
      sql_filter +=` where pcode IN (${pcodelists.join(',')}) OR fcode IN (${pcodelists.join(',')})`
    }
    sql += sql_filter;
    sql += ' ORDER BY updatetime DESC,id ASC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let list = await Exec(sql);
    let peos = [];
    if (list && list.length) {
      let codestr = _.uniq(_.compact(_.pluck(list, 'pcode').concat(_.pluck(list, 'fcode')))).join(',');
      let execsql = 'SELECT code,nickname,avator FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }
    list = _.map(list, function (item) {
      let pdata = _.find(peos, function (po) {
        return po.code == item.pcode;
      })
      item.pdata = pdata;
      let fdata = _.find(peos, function (po) {
        return po.code == item.fcode;
      })
      item.fdata = fdata;
      item.updatetime = formatDateTime(item.updatetime);
      delete item.createtime;
      return item;
    });

    let total = await Execsql_Count(`SELECT count(1) as total FROM hzz_feedbacks   `+ sql_filter);
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.info('-----feedback--feedList--反馈列表异常,', error)
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

module.exports = {
  feedAdd,
  feedList
}